﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 登录注册功能_sqlserver
{
    public partial class RegisterForm : Form
    {
        public RegisterForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 把注册信息提交到数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Zhucebutton_Click(object sender, EventArgs e)
        {
            string username = UsernametextBox.Text;
            string password = "";
            if (PasswordtextBox1.Text==PasswordtextBox2.Text && !string.IsNullOrEmpty(PasswordtextBox1.Text))
            {
                 password = PasswordtextBox1.Text;
            }
            else {
                MessageBox.Show("两次输入不一致请重新输入");
                return;
            }
            string nicheng = NichengtextBox.Text;
            string gender = "";
            if (ManradioButton.Checked == true || WomanradioButton.Checked == true) {
                if (ManradioButton.Checked == true)
                {
                    gender = "1";
                } else if (WomanradioButton.Checked == true) {
                    gender = "2";
                }

            } else {
                MessageBox.Show("选择性别");
                return;
            }
            UserTModelForEF userModel = new UserTModelForEF(username,password,gender,nicheng);

            //获取完数据后执行数据库插入操作
            int i = -1;//记录影响多少行
            using (MyDbContext mydb =new MyDbContext()) {
                int UserNamecount =mydb.UserTForWinform.Count(X => X.Username == username);
                if (UserNamecount == 0)
                {
                    mydb.UserTForWinform.Attach(userModel);
                    mydb.Entry(userModel).State = System.Data.Entity.EntityState.Added;
                    i = mydb.SaveChanges();
                }
                else {
                    MessageBox.Show("用户名重复");
                    return;
                }
               
            }
            if (i < 0)
            {
                MessageBox.Show("注册失败");
            }
            else {
                MessageBox.Show("注册成功");
            }
            this.Close();
        }

        private void RegisterForm_Load(object sender, EventArgs e)
        {

        }
    }
}
